package com.droid.library.widget.recyclerview;

import android.support.v7.widget.RecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * RecyclerView基类
 *
 * @author wangheng 
 */

public abstract class BaseDataRecyclerAdapter<T extends Serializable> extends RecyclerView.Adapter<BaseViewHolder> {
    private List<T> mList;
    /**
     * 重设数据集
     *
     * @param list list
     */
    public synchronized void resetDataList(List<T> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    public synchronized void removeItem(T item) {
        if (mList != null) {
            mList.remove(item);
            notifyDataSetChanged();
        }
    }

    public synchronized void removeItemAt(int position) {
        if (mList != null && position < mList.size() && position >= 0) {
            mList.remove(position);
            notifyDataSetChanged();
        }
    }

    public synchronized void replaceItem(int position, T item) {
        if (mList == null) {
            return;
        }
        if (position >= mList.size() || position < 0) {
            return;
        }
        mList.set(position, item);
    }

    public synchronized void clear() {
        if (null != mList && 0 != mList.size()) {
            mList.clear();
            notifyDataSetChanged();
        }
    }

    public synchronized void addItem(T item) {
        if (mList != null) {
            mList.add(item);
        } else {
            mList = new ArrayList<>();
            mList.add(item);
        }

        notifyDataSetChanged();
    }

    public synchronized void addItemAt(int position, T item) {
        if (mList != null) {
            if (mList.size() == 0) {
                mList.add(item);
            } else {
                if (position >= mList.size()) {
                    mList.add(item);
                } else if (position >= 0) {
                    mList.add(position, item);
                }
            }
        } else {
            mList = new ArrayList<>();
            mList.add(item);
        }

        notifyDataSetChanged();
    }

    /**
     * 追加列表
     *
     * @param list list
     */
    public synchronized void appendList(List<T> list) {
        if (mList != null) {
            mList.addAll(list);
        } else {
            mList = list;
        }
        notifyDataSetChanged();
    }

    public synchronized List<T> getItemList() {
        return mList;
    }

    protected T getRealItemAtPosition(int position) {
        if(mList == null){
            return null;
        }
        return mList.get(position);
    }

    public int getRealItemCount(){
        if(mList == null){
            return 0;
        }
        return mList.size();
    }
}
